class Compiler {
  constructor(vm){
    this.el = vm.$el
    this.vm = vm
    this.compile(this.el)
  }
  //编译模板，处理文本节点和元素节点
  compile(el) {
    let childNodes = el.childNodes
    Array.from(childNodes).forEach(node => {
      if(this.isTextNode(node)) {
        this.compileText(node)
      } else if(this.isElementNode(node)) {
        this.compileElement(node)
      }

      // 判断node是否有子节点，如果有，递归调用compile
      if(node.childNodes && node.childNodes.length > 0) {
        this.compile(node)
      }
    })
  }
  // 编译元素节点，处理指令
  compileElement(node) {
    // 遍历所有属性节点
    Array.from(node.attributes).forEach(attr => {
      // 判断是否是指令
      let attrName = attr.name
      if(this.isDirective(attrName)) {
        // v-text -->  text
        attrName = attrName.substr(2)
        let key = attr.value
        this.update(node, key, attrName)
      }
    })
  }
  update(node, key, attrName){
    let updateFn = this[attrName + 'Update']
    let event = null
    if(attrName.includes(':')) {
      updateFn = this['onUpdate']
      event = attrName.substr(attrName.indexOf(':') + 1)
    }
    updateFn && updateFn.call(this, node, this.vm[key], key, event)
  }
  // 用来处理v-text指令
  textUpdate(node, value, key){
    node.textContent = value
    new Watcher(this.vm, key, newVal => node.textContent = newVal)
  }
  // 处理v-model
  modelUpdate(node, value, key) {
    node.value = value
    new Watcher(this.vm, key, newVal => node.value = newVal)
    // 双向绑定
    node.addEventListener('input', () => {
      this.vm[key] = node.value
    })
  }

  // 处理 v-html指令
  htmlUpdate(node, value, key) {
    node.innerHTML = value
    new Watcher(this.vm, key, newVal => node.innerHTML = newVal)
  }

  // 处理v-on指令
  onUpdate(node, value, key, event) {
    node.addEventListener(event, value)
  }

  compileText(node) {
    // console.dir(node)
    let reg = /\{\{(.+?)\}\}/
    let value = node.textContent
    if(reg.test(value)) {
      let key = RegExp.$1.trim()
      node.textContent = value.replace(reg, this.vm[key])

      // 创建watcher对象
      new Watcher(this.vm, key, newVal => node.textContent = newVal)
    }
  }
  isDirective(attrName) {
    return attrName.startsWith('v-')
  }
  isTextNode(node) {
    return node.nodeType === 3
  }
  isElementNode(node) {
    return node.nodeType === 1
  }
}